package com.tmt.im.wallet.config;

import com.alibaba.fastjson2.filter.ValueFilter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import com.tmt.im.wallet.config.beans.*;
import com.tmt.springboot.common.restful.ExecuteResult;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/23 13:08
 * @Version 1.0
 **/
@Configuration
@EnableConfigurationProperties({SensitiveKeysProperties.class,
        CurrentServiceProperties.class,
        ClientInfoProperties.class,
        RedPackageRuleProperties.class, YunXinProperties.class})
public class WebConfig {

    static {
        ExecuteResult.SUCCESS_CODE = 200;
    }

    private SensitiveKeysProperties sensitiveKeysProperties;

    private YunXinProperties yunXinProperties;

    public WebConfig(SensitiveKeysProperties sensitiveKeysProperties,
                     YunXinProperties yunXinProperties) {
        this.sensitiveKeysProperties = sensitiveKeysProperties;
        this.yunXinProperties = yunXinProperties;
    }

    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        //1.需要先定义一个 convert 转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        //2. 添加fastJson的配置信息
        List<MediaType> supportMediaTypeList = new ArrayList<>();
        supportMediaTypeList.add(MediaType.APPLICATION_JSON);

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonConfig.setReaderFilters(new TimestampToLongFilter());

        fastConverter.setFastJsonConfig(fastJsonConfig);
        fastConverter.setSupportedMediaTypes(supportMediaTypeList);
        fastConverter.setDefaultCharset(StandardCharsets.UTF_8);

        return new HttpMessageConverters(fastConverter);
    }

    private static final class TimestampToLongFilter implements ValueFilter {
        @Override
        public Object apply(Object object, String name, Object value) {
            if (value instanceof Timestamp) {
                return ((Timestamp) value).getTime();
            }
            return value;
        }
    }

}
